<?php

namespace App\Jobs;

use App\Service\Redis\RedisBaseService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Log;

class UserKsDayRankJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Execute the job.
     *
     * @param RedisBaseService $redisBaseService
     * @return void
     * @throws \RedisException
     */
    public function handle(RedisBaseService $redisBaseService)
    {
        /**
         * 坚持天数
         */
        $ksList = DB::table('user')->whereNotNull('ksDaysCount')->orderByDesc('ksDaysCount')->limit(15)->get();
        foreach ($ksList as $item) {
            $rate = 0;
            $rightCount = 0;
            $wrongCount = 0;
            $qLogs = DB::table('qh_user_question_logs')->where('userId', $item->id)->get();
            foreach ($qLogs as $log) {
                if ($log->result == 1) $rightCount +=1;
                if ($log->result == 2) $wrongCount +=1;
            }
            $sum = $rightCount + $wrongCount;
            if ($sum > 0) {
                $rate = round($rightCount / $sum, 2);
            }
            $item->learnQuestionCount = $redisBaseService->getUserLearnQuestionCount($item->id);
            $item->questionRate = $rate;
            $item->learnQuestionCountOfToday = $item->learnQuestionOfLastTime ? (Carbon::createFromTimestamp($item->learnQuestionOfLastTime)->isToday() ? $item->learnQuestionCountOfToday : 0) : 0;
        }

        // 存入缓存
        \Cache::put('rank:userKsDaysRank', serialize($ksList), 1800);
        Log::debug('[JOB]-UserKsDayRankJob:DONE', $ksList);
    }
}
